package com.hmdp.utils;

import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;

import java.util.Collections;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * ClassName: SimpleRedisLock
 * Package:
 * Description:
 *
 * @Author pupu
 * @Create 2025/9/17 23:43
 * @Version 1.0
 */
public class SimpleRedisLock implements ILock {

    private StringRedisTemplate stringRedisTemplate;
    private String name;
    private static final String LEY_PREFIX= "lock:";
    private static final String ID_PREFIX = UUID.randomUUID().toString();
    private static final DefaultRedisScript<Long> UNLOCK_LUA;
    static {
        UNLOCK_LUA = new DefaultRedisScript<>();
        UNLOCK_LUA.setLocation(new ClassPathResource("unlock.lua"));
        UNLOCK_LUA.setResultType(Long.class);
    }
    public SimpleRedisLock(String name,StringRedisTemplate stringRedisTemplate) {
        this.name = name;
        this.stringRedisTemplate = stringRedisTemplate;
    }
    @Override
    public boolean tryLock(long timeoutSec) {
        //获取线程id
        String threadId = ID_PREFIX +Thread.currentThread().getId();
        //获取锁
        Boolean success = stringRedisTemplate.opsForValue().setIfAbsent(LEY_PREFIX + name,threadId,timeoutSec, TimeUnit.SECONDS);
        return Boolean.TRUE.equals(success);
    }

    public void unlock() {
        //调用lua脚本
        stringRedisTemplate.execute(
                UNLOCK_LUA,
                Collections.singletonList(LEY_PREFIX + name),
                ID_PREFIX +Thread.currentThread().getId());
    }

  /*  @Override
    public void unlock() {
        //释放锁
        //获取线程标识
        String threadId = ID_PREFIX +Thread.currentThread().getId();
        //获取锁的值
        String currentLockValue = stringRedisTemplate.opsForValue().get(LEY_PREFIX + name);
        //判断是不是当前线程的锁
        if(!threadId.equals(currentLockValue)){
            throw new RuntimeException("解锁的不是当前线程的锁");
        }
        stringRedisTemplate.delete(LEY_PREFIX + name);
    }*/
}
